using System;
using System.Collections.Generic;
using System.Linq;
using Tools.Domain.Common.Repositories.Contracts;
using Webshop20.Domain.Stock.Core;
using Webshop20.Domain.Stock.DataTransferObjects;

namespace Webshop20.Domain.Stock.Services
{
    public class GoodReserverationService : IGoodReservationService
    {
        private IRepository<Good> goods;

        public GoodReserverationService(IRepository<Good> goods)
        {
            this.goods = goods;
        }

        public IEnumerable<FailedReservations> ReserveGoodsInStock(IEnumerable<AttemptedReservation> attemptedReservations)
        {
            var failedReservations = new List<FailedReservations>();

            foreach (var attemptedReservation in attemptedReservations)
            {
                var good = goods.Find(g => g.ProductCode == attemptedReservation.ProductID).First();
                int actualReservations = good.TryReserveItem(attemptedReservation.Quantity);
                if(actualReservations < attemptedReservation.Quantity)
                    failedReservations.Add(new FailedReservations(attemptedReservation.ProductID, attemptedReservation.Quantity ,actualReservations));
            }

            return failedReservations;
        }
    }
}